<template>
  <div class="tw-libmobiletabs"
    :class="[`x${_uid}`,`${type==='round'?'xround':''}`]">
    <van-tabs
      v-model="active"
      :color="lineColor"
      :background="background"
      :line-height="lineHeight"
      :ellipsis="ellipsis"
      @change="change">
      <van-tab
        v-for="(tab, idx) in tabs"
        :key="idx"
        :title="tab.label">
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>

import props from './props'

export default {
  name: 'lib-mobile-tabs',

  props,

  data() {
    return {
      active: 0,
      val: null
    }
  },

  computed: {
    style () {
      return {
        color: this.color,
        background: this.background,
        height: this.height,
        fontSize: this.tabFontSize,
        activeColor: this.activeColor,
        activeBg: this.activeBg,
        tabNavSeesaw: this.tabNavSeesaw,
        tabNavAbout: this.tabNavAbout
      }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root.tw-libmobiletabs .van-tabs {
          background: ${this.background};
          padding: ${this.tabNavSeesaw} ${this.tabNavAbout};
        }

        ::root.tw-libmobiletabs .van-tab {
          color:  ${this.color};
          font-size: ${this.tabFontSize};
        }

        ::root.tw-libmobiletabs .van-tabs--line .van-tabs__wrap {
          height: ${this.height};
        }

        ::root.tw-libmobiletabs.xround .van-tab--active {
          color: ${this.activeColor};
          background: ${this.activeBg} !important;
          border-radius: ${parseInt(this.height) / 2 + (this.height + '').replace(/^\d+/, '')};
        }
      `

      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    change() {
      this.val = this.tabs[this.active].value
      this.$emit('input', this.tabs[this.active].value)
      this.$emit('change', this.tabs[this.active].value)
    },

    setActiveTab () {
      if (this.val !== this.value) {
        for (let i = 0; i < this.tabs.length; i++) {
          if (this.tabs[i].value === this.value) {
            this.val = this.value
            this.active = i
            break
          }
        }
      }
    }
  },

  mounted () {
    this.setStyle()
  },

  created () {
    this.setActiveTab()
  },

  watch: {
    value () {
      this.setActiveTab()
    },

    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
